package com.forehope.portal.controller;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.commons.formfile.FormFileUtil;
import com.actionsoft.bpms.commons.formfile.model.FormFileModel;
import com.actionsoft.bpms.commons.formfile.model.delegate.FormFile;
import com.actionsoft.bpms.commons.mvc.view.ResponseObject;
import com.actionsoft.bpms.server.RequestParams;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.server.fs.DCContext;
import com.actionsoft.bpms.server.fs.dc.DCConst;
import com.actionsoft.bpms.server.fs.dc.DCProfileManager;
import com.actionsoft.sdk.local.SDK;
import com.alibaba.fastjson.JSONObject;
import com.forehope.portal.aslpUtil.CMSUtil;
import com.forehope.portal.model.NavModel;
import jodd.util.StringUtil;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class PortalGroupUtli {
    /**
     * 处理数据
     */
    public Map<String, Object> dueData(UserContext userContext, RequestParams requestParams, String modelId) {
        Map<String, Object> resultMap = new HashMap<>();

        /**
         * 处理数据
         */
        String type = requestParams.get("type");
        String queryData = requestParams.get("query");
        JSONObject query = JSONObject.parseObject(queryData);
        int nowPage = query.getInteger("nowPage");
        int pageNum = query.getInteger("pageNum");
        //查询字段
        JSONObject fieldJSON = query.getJSONObject("fieldQuery");
        //排序字段
        JSONObject orderJSON = query.getJSONObject("order");


        //处理查询
//        List<JSONObject> resultList = this.filterData(userContext, fieldJSON, modelId,nowPage,pageNum,type);
        Map<String, Object> result = this.filterData(userContext, fieldJSON, modelId, nowPage, pageNum, type);
        List<JSONObject> resultList = (List<JSONObject> )result.get("data");
        int count = Integer.valueOf(result.get("count").toString());
        resultMap.put("totalNum", count);

        //处理排序
        this.orderUtil(orderJSON, resultList);
        List<JSONObject> list = resultList;
        //处理分页
        if (resultList != null && resultList.size() > 0) {
            list = this.subList(resultList, pageNum, nowPage);
        }
        resultMap.put("resultData", list);
        return resultMap;
    }


    /**
     * 分页
     */
    public List<JSONObject> subList(List<JSONObject> list, int pageSize, int pageNum) {
        int count = list.size();
        int pages = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
        int start = pageNum <= 0 ? 0 : (pageNum > pages ? (pages - 1) * pageSize : (pageNum - 1) * pageSize);
        int end = pageSize;
        return list.stream().skip(start).limit(pageSize).collect(Collectors.toList());
    }


    /**
     * 排序
     */
    public void orderUtil(JSONObject orderJSON, List<JSONObject> resultList) {

        /**
         * 处理排序数据
         */
        String titleOrder = orderJSON.getString("title");
        String publisherOrder = orderJSON.getString("pulisher");
        String signerOrder = orderJSON.getString("signer");
        String deptOrder = orderJSON.getString("dept");
        String releaseTimeOrder = orderJSON.getString("releaseTime");


        List<String> sortProperties = new ArrayList<>();
        //动态指定要排序的属性字段
        Map<String, Boolean> sortOrders = new HashMap<>();
        //动态指定属性字段对应的排序顺序（true表示降序，false表示升序）

        if (StringUtil.isNotEmpty(releaseTimeOrder)) {
            sortProperties.add("releaseTime");
            if ("asc".equals(releaseTimeOrder)) {
                sortOrders.put("releaseTime", true);
            } else {
                sortOrders.put("releaseTime", false);
            }
        }
        if (StringUtil.isNotEmpty(titleOrder)) {
            sortProperties.add("msgTitle");
            if ("asc".equals(releaseTimeOrder)) {
                sortOrders.put("msgTitle", true);
            } else {
                sortOrders.put("msgTitle", false);
            }
        }
        if (StringUtil.isNotEmpty(deptOrder)) {
            sortProperties.add("departmentName");
            if ("asc".equals(releaseTimeOrder)) {
                sortOrders.put("departmentName", true);
            } else {
                sortOrders.put("departmentName", false);
            }
        }

        // 构建Comparator链
        Comparator<JSONObject> comparator = null;
        for (int i = 0; i < sortProperties.size(); i++) {
            final int propertyIndex = i;
            Comparator<JSONObject> propertyComparator = Comparator.comparing(
                    (JSONObject o) -> o.getString(sortProperties.get(propertyIndex)),
                    String.CASE_INSENSITIVE_ORDER
            );

            if (sortOrders.get(sortProperties.get(propertyIndex))) {
                propertyComparator = propertyComparator.reversed();
            }

            if (comparator == null) {
                comparator = propertyComparator;
            } else {
                comparator = comparator.thenComparing(propertyComparator);
            }
        }
        if (sortProperties != null && sortProperties.size() > 0) {
            Collections.sort(resultList, comparator);
        }
    }


    /**
     * 筛选查询
     */

    public Map<String, Object> filterData(UserContext userContext, JSONObject fieldJSON, String modelId, int nowPage, int pageNum, String type) {
        Map<String, Object> map = new HashMap<>();
        /**
         * 处理二级查询数据
         */
        String title = fieldJSON.getString("title");
        String num = fieldJSON.getString("num");
        String publisher = fieldJSON.getString("pulisher");
        String signer = fieldJSON.getString("signer");
        String dept = fieldJSON.getString("dept");
        String releaseTime = fieldJSON.getString("releaseTime");
        /**
         * 处理三级查询数据（发布时间）
         */
        JSONObject releaseTimeJSON = JSONObject.parseObject(releaseTime);
        String beginTime = releaseTimeJSON.getString("beginTime");
        String endTime = releaseTimeJSON.getString("endTime");
        /**
         * 处理查询数据
         */
        CMSUtil cmsUtil = new CMSUtil();
        ResponseObject data = cmsUtil.getCmsDataByModeule(modelId, userContext.getSessionId(), nowPage, pageNum, type);
        Map dataList = data.getData(Map.class);
        List<JSONObject> list = (List<JSONObject>) dataList.get("datalist");
        int count = Integer.valueOf(dataList.get("pageCount").toString());
        Stream<JSONObject> queryResult = list.stream().filter(jsonObject -> jsonObject.getString("msgTitle").contains(title)
                && jsonObject.getString("departmentName").contains(dept)
        );
        List<JSONObject> resultList = queryResult.collect(Collectors.toList());
        map.put("data", resultList);
        map.put("count", count);
        return map;
    }

    public NavModel setNavModelData(JSONObject jsonObject) {
        NavModel navModel1 = new NavModel();
        navModel1.setAppId(jsonObject.getString("appId"));
        navModel1.setDesc(jsonObject.getString("desc"));
        navModel1.setExt1(jsonObject.getString("ext1"));
        navModel1.setExt2(jsonObject.getString("ext2"));
        navModel1.setHiddenPortal(jsonObject.getBooleanValue("hiddenPortal"));
        navModel1.setIcon16(jsonObject.getString("icon16"));
        navModel1.setIcon64(jsonObject.getString("icon64"));
        navModel1.setIcon96(jsonObject.getString("icon96"));
        navModel1.setId(jsonObject.getString("id"));
        navModel1.setName(jsonObject.getString("name"));
        navModel1.setNotifier(jsonObject.getString("notifier"));
        navModel1.setUrl(jsonObject.getString("url"));
        return navModel1;
    }

    public Set<String> getDatesBetween(Date startDate, Date endDate) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        List<Date> dates = new ArrayList<>();
        dates.add(startDate);
        dates.add(endDate);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);
        while (calendar.getTime().before(endDate)) {
            dates.add(calendar.getTime());
            calendar.add(Calendar.DATE, 1);
        }
        Set<String> resultSet = new HashSet<>();
        for (Date date : dates) {
            resultSet.add(simpleDateFormat.format(date));
        }
        return resultSet;
    }

    public void ystp(UserContext uc, String bindid) throws IOException {
        BO bo = SDK.getBOAPI().query("BO_EU_PORTAL_PHOTO").bindId(bindid).detail();
        List<FormFile> files = SDK.getBOAPI().getFiles(bo.getId(), "FILE_PHOTO");
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        InputStream inputStreamResult = null;
        try {
            if (files != null && files.size() > 0) {
                for (FormFile formFile : files) {
                    DCContext fileDc = new DCContext(uc, DCProfileManager.getDCProfile(formFile.getAppId(), DCConst.REPOSITORY_UI_FILE), formFile.getAppId(), formFile.getId(), formFile.getBoItemName(), formFile.getFileName());
                    InputStream inputStream = SDK.getDCAPI().read(fileDc);
                    BufferedImage originalImage = ImageIO.read(inputStream);
                    // 获取原始图片的宽度和高度
                    int width = originalImage.getWidth();
                    int height = originalImage.getHeight();
                    int newW = (int) (width * 0.5);
                    int newY = (int) (height * 0.5);

                    // 创建一个新的缩放后的图片对象
                    BufferedImage compressedImage = new BufferedImage(newW, newY, BufferedImage.TYPE_INT_RGB);
                    // 将原始图片绘制到缩放后的图片对象上，并设置压缩质量参数为0.9(范围为0-1,值越小表示压缩率越高)
                    Graphics2D g = compressedImage.createGraphics();
                    g.drawImage(originalImage, 0, 0, newW, newY, null);
                    g.dispose();
                    // 将压缩后的图片写入到新的文件中
                    ImageIO.write(compressedImage, "jpg", byteArrayOutputStream);
                    inputStreamResult = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
                    FormFileModel formFileModel = new FormFileModel();
                    formFileModel.setAppId(formFile.getAppId());
                    formFileModel.setBoId(formFile.getBoId());//新增数据的编号
                    formFileModel.setBoName(formFile.getBoName());//表名
                    formFileModel.setProcessInstId(formFile.getProcessInstId());//bindId
                    formFileModel.setBoItemName("FILE_PHOTOYS");//附件字段
                    formFileModel.setFileName(formFile.getFileName());//附件名称
                    if (SDK.getBOAPI().getFiles(formFile.getId(), "FILE_PHOTOYS").size() > 0) {
                        SDK.getBOAPI().removeFiles(formFile.getId(), "FILE_PHOTOYS");
                    }
                    SDK.getBOAPI().upFile(formFileModel, inputStreamResult);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            byteArrayOutputStream.close();
            inputStreamResult.close();
        }
    }

}
